/**
 * 游戏业务网络模块
 * */

import FPJDefine from "../../Game/FPJ/Prefabs/FPJDefine";
import { eventCustom } from "../../lib/EventCustom";
import { session } from "../Session";
import baseWebSocket from "./../../lib/Network/BaseWebSocket";
import {glUtils} from "../../lib/GLUtils";


export default class GameHallNetwork extends baseWebSocket {
	//_ip: "";

	constructor() {
		super();
		var cfg = cc.vv.GLNetDataModel.getGameHallCfg();
		if (!cfg) {
			return;
		}
		console.log(
			"--------gameserver host: " + cfg.hall_ip + " post:" + cfg.hall_port
		);
		var tar_ip = cfg.hall_ip;
		var tar_port = cfg.hall_port; //"37021"/"37022";
		//this._ip = cfg.hall_ip;
		this._port = cfg.hall_port;
		console.log("-----tar_ip: " + tar_ip + "   tar_port: " + tar_port);

		if (!cc.vv.NetGameHall) {
			console.log("WebSocket init gameHallNetWork");
			this.init(tar_ip, tar_port);
		}
		// cc.vv.NetGameHall = this;
	}
	onOpen() {
		super.onOpen();
		// if(cc.vv.NetGameHall){
		//     console.log("WebSocket_________open____close______");
		//     cc.vv.NetGameHall.close();
		// }
		console.log("WebSocket_________open____hall");
		//cc.vv.NetGameHall = this;

		cc.vv.UIMgr.open(cc.vv.GLConfig.waiting_path);
		this.sendEnterGame();

	}

	close() {
		super.close();
		console.log("WebSocket_________close____hall");
		// cc.vv.NetGameHall = null;
	}

	reConnect() {
		console.log("WebSocket_________reConnect____hall");
		super.reConnect();
		cc.vv.NetGameHall = null;
		new cc.vv.netgamehall();
	}

	/**
	 * 通知有玩家申请解散房间
	 * */
	ApplyDisbandNtc(data) {
		if (data.playerdisbandlist.length == 0) {
			// 房主自己在未开始解散房间
			cc.vv.GLUtils.showTips("房主已解散房间", 1);
			return;
		}
	}
	//请求更新玩家信息
	sendUpdateinfo(data, cb) {
		var playerData = cc.vv.session.getPlayer();

		if (data.loge == undefined) {
			data.loge = playerData.logo;
		}
		if (data.sex == undefined) {
			data.sex = playerData.sex;
		}
		var msg = {
			cmd: "Updateinfo",
			rolename: data.rolename || playerData.rolename,
			logo: data.logo,
			phone: data.phone || playerData.phone,
			sex: data.sex,
			des: data.des || playerData.des
		};
		this.send("Updateinfo", msg, cb || this.receiveUpdateinfo.bind(this));
	}
	//请求更新玩家信息返回
	receiveUpdateinfo(error, data) {
		if (error) {
			cc.vv.GLUtils.showTips(data.errcodedes);
			return;
		}
		cc.vv.session.updatePlayer(data);
		cc.vv.GlobalMsg.Send(
			cc.vv.GLDefine.MsgKey.Hall,
			cc.vv.GLDefine.MsgType.L_update_player_info
		);
	}
	//请求进入游戏大厅
	sendEnterGame() {
		var _accountInfo = cc.vv.GLUtils.getAccountInfo();

		if (!_accountInfo) {
			cc.game.end();
			return;
		}

		var brand = cc.vv.GLSDKMgr.getDeviceBrand();
		var model = cc.vv.GLSDKMgr.getSystemModel();
		var auth_type = cc.vv.GLDefine.EAuthType.PHONE_ACCOUNT;
		if (_accountInfo.logintoken) {
			auth_type = cc.vv.GLDefine.EAuthType.ACCOUNT_TOKEN;
		}
		var enterGameData = {
			cmd: "EnterGame",
			//	device_info: _uuid,
			logintoken: _accountInfo.logintoken || "",
			user_name: _accountInfo.phone_num,
			auth_type: auth_type,
			login_location: "",
			login_device_type: model,
			login_device_imei: brand,
			login_ip: "",
			vcode: _accountInfo.vcode || "",
			registration_id: cc.vv.GLSDKMgr.getRegistrationID() || ""
		};
		var _client_ip = cc.vv.GLSDKMgr.getClientIp();
		if (_client_ip) {
			enterGameData.login_ip = _client_ip;
		}
		cc.vv.GLUtils.getAdress(_client_ip, function (address) {
			enterGameData.login_location = address;
			this.send("EnterGame", enterGameData, this.receiveEnterGame.bind(this));
		}.bind(this));

	}
	receiveEnterGame(error, data) {
		cc.vv.NetGameHall = this;
		console.log("___receiveEnterGame______");
		cc.vv.UIMgr.close(cc.vv.GLConfig.waiting_path, cc.vv.UIMgr.closeType.hide);
		if (data.isreauth && data.isreauth == 1) {
			console.log("token过期, 需要重新认证");
			cc.vv.GLUtils.showTips("token过期, 需要重新认证");
			//todo 重新走登录
			// if (cc.vv.Login) {
			// 	console.log("cc.vv.Login = ",cc.vv.Login);
			// 	if (cc.vv.NetGameHall) {
			// 		console.log("cc.vv.NetGameHall = ",cc.vv.NetGameHall);
			// 		cc.vv.NetGameHall.close(true);
			// 		cc.vv.NetGameHall = null;
			// 	}
			// 	cc.vv.Login.relogin();
			// }
			if(cc.vv.sceneName == "Game"){
				cc.vv.sceneMgr.openScene("hall", null, () => {
					cc.vv.sceneName = "Hall";
					glUtils.repetLogin(true);
				});
			}else {
				glUtils.repetLogin(true);
			}
			return;
		}
		if (error == "您的账号异常，请联系客服") {
			cc.vv.GLUtils.showAlert1(error, function () {
				if (cc.vv.Login) {
					if (cc.vv.NetGameHall) {
						cc.vv.NetGameHall.close(true);
						cc.vv.NetGameHall = null;
					}
					cc.vv.GLUtils.clearAccountInfo();
					cc.vv.Login.relogin();
				} else {
					cc.vv.GLUtils.changeAccount();
				}
			})

			return;
		}
		if (error) {
			this.receiveEnterGameFailed(data);
			return;
		}
		this.openHeartBeat();


		cc.vv.session.updatePlayer(data.baseinfo);
		cc.vv.session.setConfig(data.config);
		cc.vv.chatMgr.setRid();
		cc.vv.GLDefine.firstChargeGiftData = data.firstchargegift;
		cc.vv.GLDefine.giftData.vip = data.ad_vip_coin;
		cc.vv.GLDefine.giftData.normal = data.ad_player_coin;
		if (cc.vv.sceneName == "Game" && FPJDefine.currentTableId) {  // 当前游戏是打开状态
			let tables_id = FPJDefine.currentTableId;
			let sendEnterTable = () => {
				let ATTEnterData = {}
				this.send("ATTEnterGame", ATTEnterData, (error, data) => {
					FPJDefine.resetAllData();
					FPJDefine.room_list = data.room_list; //房间列表
					FPJDefine.player_list = data.player_list;// 玩家列表
					FPJDefine.initAllTable();
					FPJDefine.checkVistor()
					cc.systemEvent.emit("EnterTable");
					let layer_list = JSON.parse(JSON.stringify(FPJDefine.player_list))
					let intable = false;
					for (var s = 0; s < layer_list.length; s++) {
						if (layer_list[s]["rid"] == cc.vv.session.getRid()) {
							let play_now = layer_list[s]["play_now"]
							if (play_now) {
								intable = true;
								break;
							}
						}
					}
					//如果在座子中
					if (intable) {
						cc.vv.GLUtils.sendRequest("ATTEnterTable", {
							table_id: tables_id
						}, (error, data) => {
							if (!error) {
								if (data.errorcode) {
									cc.vv.GLUtils.showTips(data.errordes);
								} else {
									cc.vv.audioUtil.stopAll()
									FPJDefine.currentState = data["table_data"]["status"]
									FPJDefine.setTableDetail(data.table_data);
									FPJDefine.setcurrentTableId(tables_id)
									cc.vv.eventCustom.emit("resetTable");
								}
							}
						});
					} else {//不在座子中  退到大厅
						cc.vv.audioUtil.stopAll();
						cc.vv.sceneMgr.openScene("hall", null, () => {
							cc.vv.sceneName = "Hall";
							cc.vv.UIMgr.close("Game/FPJ/FPJ");
							//刷新大厅桌子
							cc.vv.eventCustom.emit("refreshHallTable");
						});

					}

				});
			}
			sendEnterTable()
		} else {
			// 更新用户头像等
			//进入大厅;
			cc.vv.sceneMgr.openScene("hall", null, () => {
				cc.vv.UIMgr.close(cc.vv.GLConfig.waiting_path, cc.vv.UIMgr.closeType.hide);
				let ATTEnterData = {}
				this.send("ATTEnterGame", ATTEnterData, (error, data) => {
					FPJDefine.resetAllData();
					FPJDefine.room_list = data.room_list; //房间列表
					FPJDefine.player_list = data.player_list;// 玩家列表
					FPJDefine.initAllTable();
					FPJDefine.checkVistor();
					cc.vv.eventCustom.emit("openHall");
					//刷新大厅桌子
					cc.vv.eventCustom.emit("refreshHallTable");
					cc.systemEvent.emit("EnterTable");
				});
				if (data.new_player == 1) {
				}
			});
		}
	}
	receiveEnterGameFailed(data) {
		cc.vv.GLUtils.clearAccountInfo();
		if (cc.vv.NetGameHall) {
			cc.vv.NetGameHall.close(true);
			cc.vv.NetGameHall = null;
		}
		cc.vv.eventCustom.emit("entergamefail");
	}
	/**
	 * 请求断线重连进入桌子
	 * */
	sendReenterTable(data) {
		var msg = {
			cmd: "ReenterTable",
			roomsvr_id: data.roomsvr_id,
			roomsvr_table_address: data.roomsvr_table_address,
			gameid: data.gameid
		};
		this.send("ReenterTable", msg, function (error, data) {
			if (!error) {
				// cc.vv.GLGameStateMgr.enterGame(data);
			} else {
				cc.vv.GLUtils.showTips(data.errcodedes);
				cc.vv.GLSceneMgr.loadScene(
					cc.vv.GLDefine.getSceneNameByGameId(cc.vv.GLDefine.EGameID.GAME_HALL),
					() => {
						//  cc.vv.GLGameStateMgr.resetDataModel();
					}
				);
			}
		});
	}

	// 取得指定游自建金币场随机展示房间列表请求
	sendGetFriendCoinTableList(game_id, cb) {
		var msg = {
			cmd: "GetFriendCoinTableList",
			gameid: game_id
		};
		this.send("GetFriendCoinTableList", msg, function (error, data) {
			if (cb) {
				cb(error, data);
			}
		});
	}
	//取得非自建场游戏类型列表
	sendGetGameRooms(data, cb) {
		var msg = {
			cmd: "GetGameRooms",
			gameid: data.gameid,
			room_type: data.room_type,
			pattern: data.pattern
		};
		this.send("GetGameRooms", msg, function (error, data) {
			if (cb) {
				cb(error, data);
			}
		});
	}

	// 请求进入桌子
	sendEnterTable(data, cus_cb) {
		var msg = {
			cmd: "EnterTable",
			id: data.id,
			roomsvr_id: data.roomsvr_id,
			roomsvr_table_address: data.roomsvr_table_address,
			gameid: data.gameid || cc.vv.GLDefine.EGameID.REDBLACK,
			password: data.password || "",
			is_quickstart: data.is_quickstart || false,
			//
			room_type: 0,
			base_score: 0,
			pattern: 0
		};

		if (data.is_quickstart) {
			msg.room_type = data.room_type;
			msg.base_score = data.base_score;
			msg.pattern = data.pattern;
		}
		if (data.room_type == cc.vv.GLDefine.ERoomType.MATCH) {
			//练习场增加带入值;
			// msg.use_voucher_lottery = cc.vv.GLPageDataModel.getUseVoucherLottery();
			msg.room_type = data.room_type;
			msg.base_score = data.base_score;
			msg.pattern = data.pattern;
		}
		this.send("EnterTable", msg, cus_cb || this.receiveEnterTable.bind(this));
	}
	// 请求进入桌子返回
	receiveEnterTable(error, data) {
		cc.vv.UIMgr.close(cc.vv.GLConfig.waiting_path, cc.vv.UIMgr.closeType.hide);
		if (error) {
			this.receiveEnterTableFailed(data);
			return;
		}
		// cc.vv.GLGameStateMgr.enterGame(data);
	}
	// 进入桌子失败
	receiveEnterTableFailed(data) {
		if (data.errcode == 47) {//cc.vv.ErrorCodeDataModel.ERR_NOT_ENOUGH_MINCARRYCOIN) {
			// 金币不足todo:
			cc.vv.GLUtils.showAlert1("金币不足房间携带量");
		} else {
			if (data.errcode == 12) {//cc.vv.ErrorCodeDataModel.ERR_HAD_IN_TABLE) {
				// cc.vv.GLUtils.showAlert(data.errcodedes + ":你已经在牌桌内，是否立即返回?", function () {
				cc.vv.GLUtils.showTips("你已经在房间内,正在返回之前房间;");
				cc.vv.NetGameHall.sendReenterTable({
					roomsvr_id: data.roomsvr_id,
					roomsvr_table_address: data.roomsvr_table_address,
					gameid: data.gameid
				});
				// } function () {});
			} else {
				cc.vv.GLUtils.showTips(data.errcodedes, 2);
			}
		}
	}
	//快速开始请求, id 指定上一次所在的桌号主要用于快速换桌,如果不需要换桌逻辑填0
	sendQuickStart(gameid, room_type, base_score, pattern = 1, id = 0, cb) {
		var msg = {
			cmd: "QuickStart",
			id: id,
			gameid: gameid,
			room_type: room_type,
			base_score: base_score,
			pattern: pattern
		};
		this.send("QuickStart", msg, cb || this.receiveQuickStart.bind(this));
	}
	// 快速开始请求返回
	receiveQuickStart(error, data) {
		if (error) {
			//快速开始请求失败
			cc.vv.GLUtils.showTips(data.errcodedes, 2);
			return;
		}
		cc.vv.GLPageDataModel.setIsQuickStart(true);
		data.is_quickstart = true;
		this.sendEnterTable(data, null);
	}
	//玩家发送消息
	// 玩家发送消息
	sendSendMessage(messages, type = 1) {
		var game_id = 103; //cc.vv.GLUtils.getGameID();
		var msg = {
			cmd: "SendMessage",
			messages: messages,
			chat_type: type,
			gameid: game_id || null
		};
		this.send("SendMessage", msg, this.receiveSendMessage.bind(this));
	}
	receiveSendMessage(data) { }


	//请求玩家基本信息
	sendPlayerBaseinfo(rid, gameid = 0) {
		var msg = {
			cmd: "PlayerBaseinfo",
			rid: rid,
			gameid: gameid
		};
		this.send("PlayerBaseinfo", msg, this.receivePlayerBaseinfo.bind(this));
	}
	//请求玩家基本信息返回
	receivePlayerBaseinfo(error, data) {
		var page = cc.vv.GLPageMgr.getPage("Page_OtherInfo");
		if (page) {
			page.refreshPage(data.baseinfo);
		}
		if (data.baseinfo.rid == cc.vv.session.getRid()) {
			cc.vv.session.updatePlayer(data.baseinfo);
			cc.vv.GlobalMsg.Send(
				cc.vv.GLDefine.MsgKey.Hall,
				cc.vv.GLDefine.MsgType.L_update_player_info,
				data
			);
		}
	}
	receivePlayerBaseinfoNtc(data) {
		// 只用于保险箱数据通信 赠送时
		cc.vv.session.setBankpack(data.baseinfo.bankpack);
		cc.vv.GlobalMsg.Send(
			cc.vv.GLDefine.MsgKey.Hall,
			cc.vv.GLDefine.MsgType.L_update_player_info
		);
	}
	//请求分享奖励;
	sendRecShareAward(shareType) {
		var msg = {
			cmd: "RecShareAward",
			share_type: shareType
		};
		this.send("RecShareAward", msg, this.receiveRecShareAward.bind(this));
	}
	receiveRecShareAward(error, data) { }

	////邮件/////////////////////////////////////////////////////////
	//玩家请求领取邮件附件
	sendGetmailItemsReq(mail_key, cb) {
		var msg = {
			cmd: "GetmailItems",
			mail_key: mail_key
		};
		this.send("GetmailItems", msg, function (error, data) {
			if (cb) {
				cb(error, data);
			}
		});
	}

	//玩家请求删除邮件
	sendDeleteMailReq(mail_key, cb) {
		var msg = {
			cmd: "DeleteMail",
			mail_key: mail_key
		};
		this.send("DeleteMail", msg, function (error, data) {
			if (cb) {
				cb(error, data);
			}
		});
	}

	//玩家请求删除邮件
	sendOpenMailReq(mail_key, cb) {
		var msg = {
			cmd: "OpenMail",
			mail_key: mail_key
		};
		this.send("OpenMail", msg, function (error, data) {
			if (cb) {
				cb(error, data);
			}
		});
	}

	receiveNewmailNtc(data) {
		cc.vv.eventCustom.emit("mailadd");
	}
	//



	sendRequest(cmd, msg = { cmd: "" }, callBack: Function) {
		msg.cmd = cmd || "";
		this.send(cmd, msg, callBack);
		// this.send(cmd, msg, function (error, data) {
		// 	if (callBack) {
		// 		callBack(error, data);
		// 	}
		// });
	}

	sendGetVcode(type, phone, code) {
		var msg = {
			cmd: "GetVcode",
			//   request_code: type,
			phone_number: phone
			//  vcode: code
		};
		this.send("GetVcode", msg, this.receiveGetVcode.bind(this));
	}

	receiveGetVcode(error, data) {
		if (error) {
			cc.vv.GlobalMsg.Send(
				cc.vv.GLDefine.MsgKey.Hall,
				cc.vv.GLDefine.MsgType.L_receive_get_vcode,
				data
			);
		}
		cc.vv.GLUtils.showTips(data.errcodedes, 2);
	}

	////////////////////////兑换相关///////////////////////////////

	//////////////////兑换/////////////////////////////////////////

	//发起兑换请求;
	sendExchangeReq(data, cb) {
		var msg = {
			cmd: "Exchange",
			coin: data.coin,
			type: data.type
		};
		this.send("Exchange", msg, cb);
	}
	receiveExchangeRes(error, data) {
		cc.log(data);
		// cc.vv.GlobalMsg.Send(cc.vv.GLDefine.MsgKey.Hall, cc.vv.GLDefine.MsgType.L_GetWithdrawRecords, data.records);
	}

	/////////////////////////////////////////////////////////

	//////////////////推送//////////////////////////
	receiveRepeatNtc(data) {
		console.log("-------------checkConnect, to close page_reconnect   22!");
		cc.vv.UIMgr.close(cc.vv.GLConfig.reconnect_path, cc.vv.UIMgr.closeType.destory);
		var str = "系统检测到您的账户正在其他地方登录，您即将返回登录界面！";//cc.vv.GLTextMgr.getText("login_other_device");
		cc.vv.GLUtils.showAlert1(str, function () {
			cc.vv.UIMgr.closeAll();
			cc.vv.GLUtils.clearUserInfo();
			cc.vv.GLUtils.repetLogin(true);
		});
		if (cc.vv.NetGameHall) {
			cc.vv.NetGameHall.close(true);
		}
	}

	///
	receiveCloseNtc(data) {
		var str = "";
		if (data.code === 4001) {
			str = "系统检测到您的账户正在其他地方登录，您即将返回登录界面！";
		} else if (data.code === 4002) {
			str = data.reason;//"您的账号已经被封";
		} else if (data.code === 4003) {
			str = "服务器已关闭，请退出到登录界面！";
		}

		cc.vv.GLUtils.showAlert1(str, function () {
			if (cc.vv.Login) {
				cc.vv.GLUtils.clearAccountInfo();
				cc.vv.Login.relogin();

			} else {
				cc.vv.GLUtils.changeAccount();
			}
		});
		if (cc.vv.NetGameHall) {
			cc.vv.NetGameHall.close(true);
			cc.vv.NetGameHall = null;
		}


	}
	//房间内同步货币数据
	receiveTableSyncAwardsNtc(data) {
		// cc.vv.GlobalMsg.Send(cc.vv.GLDefine.MsgKey.Game, cc.vv.GLDefine.MsgType.L_game_sync_awards, data);
		//该消息仅游戏数据中心和逻辑管理器直接处理;
	}
	receivePlayerCoinNtc(data) {
		cc.vv.session.setCoin(data.coin || 0);
		cc.vv.session.setDiamond(data.diamond || 0);

		if (data.why == "turntable_receive") {
			//大转盘时延迟5秒
			cc.vv.Timer.start(5, function () {
				cc.vv.eventCustom.emit("updatePlayerInfo", data);
			}.bind(this), null);
		} else {
			cc.vv.eventCustom.emit("updatePlayerInfo", data);
		}
	}

	receiveKickoutNtc(data) { //被踢出  退出到大厅
		cc.vv.GLUtils.changeAccount();
		if (data.reason) {
			cc.vv.GLUtils.showTips(data.reason);
		}
	}

	receiveMarqueemsgNtc(data) {
		console.log("Message_MarqueemsgNtc" + JSON.stringify(data));
		cc.vv.MarqueeDataModel.addMarquee(data);
	}
	receiveRechargeNtc(data) {
		cc.vv.GlobalMsg.Send(cc.vv.GLDefine.MsgKey.Game, cc.vv.GLDefine.MsgType.L_game_recharge_ntc, data);
	}

	receiveColorpoolUpdateNtc(data) {
		cc.vv.GlobalMsg.Send(cc.vv.GLDefine.MsgKey.Game, cc.vv.GLDefine.MsgType.L_game_colorpool_update_ntc, data);
	}
	//彩池中奖通知(特殊牌型奖励)
	receiveColorpoolAwardsNtc(data) {
		cc.vv.GlobalMsg.Send(cc.vv.GLDefine.MsgKey.Game, cc.vv.GLDefine.MsgType.L_game_colorpool_Awards_ntc, data);
	}

	receiveUnbindBankNtc(data) {
		cc.vv.session.unBind(data);
		cc.vv.GlobalMsg.Send(cc.vv.GLDefine.MsgKey.Hall, cc.vv.GLDefine.MsgType.L_unbind, data);
	}

	//vip等级改变
	receiveVipLevelNtc(data) {
		cc.vv.session.setVip(data.level);
		cc.vv.eventCustom.emit("VipLevelChange");
	}
	receiveUserSelfInfoNtc(data) {
		cc.vv.eventCustom.emit("UserSelfInfo", data);
	}

	receivePayBillNtc(data) {
		cc.vv.eventCustom.emit("receivePayBillNtc", data);
	}


	receiveActiveVipNtc(data) {
		session.setVip(data.vipLevel)
		session.setExp(data.exp)
	}
	receiveSealCoinNtc(data) {
		session.setSealCoin(data.sealCoin)
		session.setUnsealCoinQuota(data.unsealCoinQuota)
		session.setVipAdditionPercent(data.vipAdditionPercent)
		eventCustom.emit("refreshSealCoin")
	}



}
